package config

import (
	"fmt"
	"github.com/spf13/viper"
	"strings"
)

type Config struct {
	Server   ServerConfig   `mapstructure:"server"`
	Database DataBaseConfig `mapstructure:"database"`
	Redis    RedisConfig    `mapstructure:"redis"`
	//App       AppConfig       `mapstructure:"app"`
	//ShortCode ShortCodeConfig `mapstructure:"shortcode"`
}

type ServerConfig struct {
	Port string `mapstructure:"port"`
}

type DataBaseConfig struct {
	Driver       string `mapstructure:"driver"`
	Host         string `mapstructure:"host"`
	Port         int    `mapstructure:"port"`
	User         string `mapstructure:"user"`
	Password     string `mapstructure:"password"`
	DBName       string `mapstructure:"dbname"`
	SSLMode      string `mapstructure:"sslmode"`
	MaxIdleConns int    `mapstructure:"max_idle_conns"`
	MaxOpenConns int    `mapstructure:"max_open_conns"`
}

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

var Cfg Config

func init() {
	// 增加环境变量控制
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv()

	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("config")

	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Sprintf("viper获取配置文件失败: %v", err))
	}
	if err = viper.Unmarshal(&Cfg); err != nil {
		panic(fmt.Sprintf("序列化配置错误！ %v", err))
	}
	fmt.Println(Cfg)
}
